<template>
  <div class="form-subform">
    <!-- start 添加按钮 -->
    <el-button
      class="add-subform-btn"
      type="primary"
      icon="el-icon-plus"
      plain
      size="mini"
      @click="createSubformFieldValue"
    >
      {{$t('common.base.addModule', {module:''})}}
    </el-button>
    <!-- end 添加按钮 -->

    <!-- start 添加子表单数据弹窗 -->
    <base-modal
      :title="title"
      @closed="reset"
      :show.sync="visible"
      min-width="700px"
      class="batch-editing-customer-dialog"
    >
      <form-builder
        v-if="visible"
        ref="form"
        :fields="fields"
        :value="form"
        @update="update"
        :mode="modeParams"
      >
      </form-builder>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="pending">
          {{$t('common.base.confirm')}}
        </el-button>
      </div>
    </base-modal>
    <!-- end 添加子表单数据弹窗 -->

    <!-- start 子表单表格 -->
    <el-table
      v-table-style
      v-if="columns.length"
      :data="subformFieldsValues"
      :highlight-current-row="false"
      header-row-class-name="common-list-table-header__v2"
      ref="multipleTable"
      border
    >
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :min-width="column.minWidth || '108px'"
        :show-overflow-tooltip="column.field !== 'name'"
        :align="column.align"
      >
        <template slot-scope="scope">
          <!-- start 附件 -->
          <template v-if="column.formType === 'attachment'">
            <template v-if="scope.row[column.field] && scope.row[column.field].length">
              <el-button type="text" size="small" @click="handleAttachmentView(column, scope.row[column.field])">{{ $t('common.base.view') }}</el-button>
            </template>
          </template>
          <!-- end 附件 -->
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.base.operation')" width="100">
        <template slot-scope="scope">
          <el-button
            @click="editSubformFieldValue(scope.row, scope.$index)"
            type="text"
            size="small"
          >
            {{$t('common.base.edit')}}
          </el-button>
          <el-button
            @click="deleteSubformFieldValue(scope.$index)"
            type="text"
            size="small"
          >
            {{$t('common.base.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- end 子表单表格 -->

    <form-attachment-view-dialog ref="attachmentView" />
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* util */
import * as FormUtil from '@src/component/form/util';
import { SUBFORM_FIELDS_ADD_LENGTH_MAX } from '../../config';
import { findComponentUpward } from '@src/util/assist';
import i18n from '@src/locales'
import FormAttachmentViewDialog from '@src/component/form/common/components/FormAttachmentViewDialog.vue';
// 表格需要过滤的控件
const TABLE_FILTER_COLUMNS = [
  // 'attachment',
  'separator',
  'info',
  'autograph',
  'location'
];
export default {
  name: 'form-subform',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      action: '',
      currentSubformIndex: null,
      form: {},
      pending: false,
      subformFieldsValues: this.value || [],
      visible: false
    };
  },
  components: {
    FormAttachmentViewDialog,
  },
  computed: {
    /** 表单模板id */
    templateId() {
      return this.$route.query.formId;
    },
    // 表单内容id
    contentBizId() {
      return this.$route.query.formContentId;
    },
    // 子表单重复性校验参数
    subformParams() {
      return {
        contentId: '',
        templateBizId: this.templateId
      };
    },
    actionText() {
      return this.action == 'create' ? i18n.t('common.base.create') : i18n.t('common.base.edit');
    },
    columns() {
      let columns = this.fields.filter(
        item => !TABLE_FILTER_COLUMNS.includes(item.formType)
      );

      columns.map(field => {
        field.label = field.displayName;
        field.field = field.fieldName;
      });
      return columns;
    },
    // 子表单数据
    fields() {
      let { subFormFieldList = [] } = this.field || {};
      return subFormFieldList.filter(f => FormUtil.isVisibleField(f));
    },
    isCreateSubform() {
      return this.action === 'create';
    },
    title() {
      return `${this.actionText}${this.field?.displayName || ''}`;
    },
    // 需要检验重复性的表单
    checkFieldMap() {
      let repeatFields = this.fields.filter(f => {
        const { isRepeat } = f.setting || {};
        if (isRepeat && isRepeat == 1) return f;
      });

      return repeatFields;
    },
    modeParams() {
      let parent = findComponentUpward(this, 'form-builder');
      if (parent?.mode == 'externalForm') {
        return 'subExternalForm';
      }
      return 'subForm';
    }
  },
  watch: {
    value(newValue) {
      this.subformFieldsValues = newValue || [];
    }
  },
  methods: {
    closeAddSubformDialog() {
      this.visible = false;
    },

    // 新增子表单
    createSubformFieldValue() {
      if (this.subformFieldsValues.length >= SUBFORM_FIELDS_ADD_LENGTH_MAX)
        return this.$message.warning(this.$t('common.form.tip.alowAddDataCount', {data1:SUBFORM_FIELDS_ADD_LENGTH_MAX}));

      this.action = 'create';
      if (this.subformFieldsValues) this.resetForm();
      this.openAddSubformDialog();
    },

    // 删除子表单
    deleteSubformFieldValue(index) {
      this.currentSubformIndex = index;
      this.subformFieldsValues.splice(this.currentSubformIndex, 1);
    },

    // 编辑子表单
    editSubformFieldValue(value, index) {
      this.currentSubformIndex = index;
      this.subformParams.contentId = value.id;

      this.form = Object.assign(
        FormUtil.initialize(this.fields, value),
        this.subformParams
      );

      this.setActionWithEdit();
      this.openAddSubformDialog();
    },

    /**
     * @description: 提交表单
     */
    async onSubmit() {
      // 校验表单必填项
      const validateRes = await this.$refs.form.validate(false);
      if (!validateRes) return;
      // 重复性表单校验
      let validateField = this.repeatRemoteValidate(this.currentSubformIndex);
      if (validateField) return this.$message.warning(validateField);

      // 新增表单
      if (this.isCreateSubform) {
        this.subformFieldsValues.push(this.form);
      } else {
        // 编辑表单
        this.$set(
          this.subformFieldsValues,
          this.currentSubformIndex,
          this.form
        );
      }
      this.closeAddSubformDialog();
      this.reset();
      this.inputForValue(this.subformFieldsValues);
    },

    // 打开弹窗
    openAddSubformDialog() {
      this.visible = true;
      this.form = Object.assign(this.form, this.subformParams);
    },
    // 重置数据
    resetForm() {
      this.currentSubformIndex = null;
      this.form = FormUtil.initialize(this.fields, {});
    },
    // 弹窗关闭重置数据
    reset() {
      this.resetForm();
      this.closeAddSubformDialog();
    },
    setActionWithCreate() {
      this.action = 'create';
    },
    setActionWithEdit() {
      this.action = 'edit';
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      this.$set(this.form, fieldName, newValue);
    },
    /* 查看附件详情 */
    handleAttachmentView(field, value) {
      this.$refs.attachmentView.open(field, value);
    },
  }
};
</script>

<style lang="scss" scoped>
.form-subform {
  .add-subform-btn {
    border-radius: 4px;
    margin-bottom: 12px;
  }
  ::v-deep  .base-modal-body {
    padding: 20px;
    // min-height: 350px;
  }
}
</style>

<style lang="scss">
.form-item.err :not(.is-success) {
  .form-item :not(.err) {
    input,
    textarea,
    .base-select-main-content {
      border-color: #e0e1e2 !important;
    }
  }

  .form-item.err {
    input,
    .base-select-main-content {
      border-color: #f56c6c !important;
    }
  }
}
</style>
